<?php

namespace app\domain\admin;

use app\model\admin\Admin;
use Exception;

class LoginDomain extends CommonDomain
{
    public function login($params): array|bool
    {
        try {
            $loginPasswordErrorNumKey = "loginPasswordErrorNum:{$params['username']}";
            $loginPasswordErrorNum = (int)cache($loginPasswordErrorNumKey);
            if ($loginPasswordErrorNum > 5) {
                throw new Exception('多次输入错误密码，请稍后重试！');
            }

            $info = app(Admin::class)->where(['username' => $params['username']])->find();
            if (!$info) {
                throw new Exception('用户信息不存在！');
            }

            if ('disable' == $info['status']) {
                throw new Exception('账户被禁用！');
            }

            if (!$info->checkPassword($params['password'])) {
                $loginPasswordErrorNum += 1;
                cache($loginPasswordErrorNumKey, $loginPasswordErrorNum, 60 * 5);

                throw new Exception('密码错误！');
            }

            $payload = [
                'id' => $info['id'],
                'group_id' => $info['group_id'],
                'username' => $info['username'],
                'phone' => $info['phone'],
                'timestamp' => time(),
            ];

            $authorization = hash('sha256', json_encode($payload, 320));
            cache("userInfo:{$authorization}", $payload, 3600 * 2);

            return [
                'authorization' => $authorization,
                'userInfo' => $payload
            ];
        } catch (\Exception $e) {
            $this->message = $e->getMessage();
            return false;
        }
    }

    public function getUserInfo(): array
    {
        try {
            $info = getUserInfo();
            return [
                'info' => $info,
                'roles' => []
            ];
        } catch (Exception $e) {
            $this->message = $e->getMessage();
            return [];
        }
    }
}